<template>
  <div class="video-chat-container">
    <div class="video-header">
      <div class="chat-info">
        <v-avatar size="32" class="mr-2">
          <v-img :src="remoteUser?.avatar || '/default-avatar.png'" />
        </v-avatar>
        <span class="chat-title">{{ remoteUser?.name || '视频通话' }}</span>
      </div>
      <div class="header-controls">
        <v-btn icon size="small" @click="minimizeWindow">
          <v-icon>mdi-minus</v-icon>
        </v-btn>
        <v-btn icon size="small" @click="closeWindow">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </div>
    </div>

    <div class="video-content">
      <div class="main-video">
        <video 
          ref="remoteVideo" 
          autoplay 
          playsinline
          class="remote-video"
        ></video>
        <div v-if="!isConnected" class="connecting-overlay">
          <v-progress-circular indeterminate color="primary"></v-progress-circular>
          <p>正在连接...</p>
        </div>
      </div>
      
      <div class="local-video-container">
        <video 
          ref="localVideo" 
          autoplay 
          playsinline 
          muted
          class="local-video"
        ></video>
      </div>
    </div>

    <div class="video-controls">
      <v-btn 
        fab 
        :color="isMuted ? 'red' : 'primary'"
        @click="toggleMute"
        class="control-btn"
      >
        <v-icon>{{ isMuted ? 'mdi-microphone-off' : 'mdi-microphone' }}</v-icon>
      </v-btn>
      
      <v-btn 
        fab 
        :color="isVideoOff ? 'red' : 'primary'"
        @click="toggleVideo"
        class="control-btn"
      >
        <v-icon>{{ isVideoOff ? 'mdi-video-off' : 'mdi-video' }}</v-icon>
      </v-btn>
      
      <v-btn 
        fab 
        color="red"
        @click="endCall"
        class="control-btn end-call"
      >
        <v-icon>mdi-phone-hangup</v-icon>
      </v-btn>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { invoke } from '@tauri-apps/api/tauri'

interface RemoteUser {
  userId: string
  name: string
  avatar: string
}

const props = defineProps<{
  remoteUser?: RemoteUser
  isIncoming?: boolean
}>()

const localVideo = ref<HTMLVideoElement>()
const remoteVideo = ref<HTMLVideoElement>()
const isConnected = ref(false)
const isMuted = ref(false)
const isVideoOff = ref(false)

let localStream: MediaStream | null = null
let peerConnection: RTCPeerConnection | null = null

// 初始化视频聊天
const initVideoChat = async () => {
  try {
    localStream = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    })
    
    if (localVideo.value) {
      localVideo.value.srcObject = localStream
    }
    
    await initWebRTC()
    
  } catch (error) {
    console.error('初始化视频聊天失败:', error)
  }
}

// 初始化WebRTC
const initWebRTC = () => {
  const configuration = {
    iceServers: [
      { urls: 'stun:stun.l.google.com:19302' }
    ]
  }
  
  peerConnection = new RTCPeerConnection(configuration)
  
  if (localStream) {
    localStream.getTracks().forEach(track => {
      peerConnection?.addTrack(track, localStream!)
    })
  }
  
  peerConnection.ontrack = (event) => {
    if (remoteVideo.value) {
      remoteVideo.value.srcObject = event.streams[0]
    }
    isConnected.value = true
  }
}

// 切换静音
const toggleMute = () => {
  if (localStream) {
    const audioTrack = localStream.getAudioTracks()[0]
    if (audioTrack) {
      audioTrack.enabled = !audioTrack.enabled
      isMuted.value = !audioTrack.enabled
    }
  }
}

// 切换视频
const toggleVideo = () => {
  if (localStream) {
    const videoTrack = localStream.getVideoTracks()[0]
    if (videoTrack) {
      videoTrack.enabled = !videoTrack.enabled
      isVideoOff.value = !videoTrack.enabled
    }
  }
}

// 结束通话
const endCall = async () => {
  if (localStream) {
    localStream.getTracks().forEach(track => track.stop())
  }
  
  if (peerConnection) {
    peerConnection.close()
  }
  
  await invoke('close_video_window')
}

// 最小化窗口
const minimizeWindow = async () => {
  await invoke('minimize_video_window')
}

// 关闭窗口
const closeWindow = async () => {
  await invoke('close_video_window')
}

onMounted(async () => {
  await initVideoChat()
})

onUnmounted(() => {
  if (localStream) {
    localStream.getTracks().forEach(track => track.stop())
  }
  if (peerConnection) {
    peerConnection.close()
  }
})
</script>

<style scoped lang="scss">
.video-chat-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  
  .chat-info {
    display: flex;
    align-items: center;
    
    .chat-title {
      color: white;
      font-weight: 500;
      font-size: 16px;
    }
  }
  
  .header-controls {
    display: flex;
    gap: 8px;
    
    .v-btn {
      color: white;
      background: rgba(255, 255, 255, 0.1);
      
      &:hover {
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }
}

.video-content {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .main-video {
    width: 100%;
    height: 100%;
    position: relative;
    
    .remote-video {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 8px;
    }
    
    .connecting-overlay {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
      color: white;
      
      p {
        margin-top: 16px;
        font-size: 16px;
      }
    }
  }
  
  .local-video-container {
    position: absolute;
    top: 24px;
    right: 24px;
    width: 200px;
    height: 150px;
    border-radius: 8px;
    overflow: hidden;
    border: 3px solid white;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    
    .local-video {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

.video-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  padding: 24px;
  background: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  
  .control-btn {
    width: 56px;
    height: 56px;
    
    &.end-call {
      width: 64px;
      height: 64px;
    }
  }
}
</style> 